import axios from 'axios'
import router from '@/router/index'
import {
  Message
} from 'element-ui'

const instance = axios.create({
  timeout: 15000
});

instance.interceptors.request.use(config => {
  if (config.url.indexOf('/admin/auth/login') === -1) {
    config.headers = config.headers || {}
    config.headers['X-Nideshop-Token'] = localStorage.getItem('token')
  }
  return config;
}, err => {
  return Promise.reject(err);
})

instance.interceptors.response.use(result => {
  if (result.data && result.data.errno !== 0) {
    Message.error(result.data.errmsg);
    if (result.data.errno === 1000) {
      localStorage.clear()
      router.replace('/login')
    }
  }
  return result.data;
}, err => {
  return Promise.reject(err);
})

export default instance;